package com.liyuan.yiqixing.controller;

import com.liyuan.yiqixing.model.ResultJsonMD;
import com.liyuan.yiqixing.model.User;
import com.liyuan.yiqixing.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileController {
    @Autowired
    AuthenticationService authenticationService;
    @Value("${file.path}")
    private String filePath;

    @PostMapping("/file/uploadAvatar")
    public void uplaodAvatar(HttpServletRequest request,
                             HttpServletResponse response) throws IOException {
        String newFileName = saveFile("imageFile", request);
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        authenticationService.updateUserAvatarUrl(user.getId(), "/" + newFileName);
        response.sendRedirect("/personal.html");

    }

    @PostMapping("/file/uploadImg")
    public ResultJsonMD uploadImg(HttpServletRequest request) throws IOException {
        String newFilename = saveFile("editormd-image-file", request);
        return new ResultJsonMD(1, "upload image success!", "/" + newFilename);
    }

    private String saveFile(String uploadFilename, HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartHttpServletRequest.getFile(uploadFilename);
        String newFilename = null;
        if (file != null) {
            String[] fileTypes = file.getContentType().split("/");
            String fileType = fileTypes[fileTypes.length - 1];
            newFilename = UUID.randomUUID().toString() + "." + fileType;
            File file1 = new File(filePath + newFilename);
            file.transferTo(file1);
        }
        return newFilename;
    }
}
